package com.jt.tenant.widget;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.Locale.CHINA;

/**
 * Created by Administrator on 2016/2/24.
 */
public class Tools {

    public static boolean isMobile(String mobiles) {

        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // ��֤�ֻ��
        m = p.matcher(mobiles);
        b = m.matches();
        return b;
        // return m.matches();

    }

    /**
     * 验证身份证号是否符合规则
     * @param text 身份证号
     * @return
     */
    public static boolean personIdValidation(String text) {

        String regx = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";

        if (TextUtils.isEmpty(text)) return false;
        else return text.matches(regx);
    }
    /**
     * @param time_stamp
     *
     */
    public static String getTime(String time_stamp){
        String time = "";
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
        if(!time_stamp.equals("")) {
            Long time_long = new Long(Long.parseLong(time_stamp));
            time = format.format(time_long);
        }
        return time;
    }

    public static String getYear(){

        SimpleDateFormat format =  new SimpleDateFormat("yyyy");

        String time = format.format(System.currentTimeMillis());

        return time;

    }

    public static String getMonth(){

        SimpleDateFormat format =  new SimpleDateFormat("MM");

        String time = format.format(System.currentTimeMillis());

        return time;

    }

    public static String getTime1(String time_stamp){

        String true_time = time_stamp.length() == 10 ? time_stamp+"000" : time_stamp;

        String time = "";
        if(!time_stamp.equals("")){
            SimpleDateFormat format =  new SimpleDateFormat("yyyy年MM月dd日  HH时mm分");
            Long time_long = new Long(Long.parseLong(true_time));
            time = format.format(time_long);
        }

        return time;
    }

    public static String getTime2(String time_stamp){

        String true_time = time_stamp.length() == 10 ? time_stamp+"000" : time_stamp;

        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm");

        if(time_stamp.equals("")){

            return "";

        }else {

            Long time_long = new Long(Long.parseLong(true_time));
            String time = format.format(time_long);
            return time;

        }

    }

    public static String getTime3(String time_stamp){

        String true_time = time_stamp.length() == 10 ? time_stamp+"000" : time_stamp;

        SimpleDateFormat format =  new SimpleDateFormat("yyyy年MM-dd");

        if(time_stamp.equals("")){

            return "";

        }else {

            Long time_long = new Long(Long.parseLong(true_time));
            String time = format.format(time_long);
            return time;
        }
    }

    public static String getTime4(String time_stamp){

        String true_time = time_stamp.length() == 10 ? time_stamp+"000" : time_stamp;

        SimpleDateFormat format =  new SimpleDateFormat("HH:mm");

        if(time_stamp.equals("")){

            return "";

        }else {

            Long time_long = new Long(Long.parseLong(true_time));

            String time = format.format(time_long);

            return time;

        }
    }

    public static String getTime5(String time_stamp){

        String true_time = time_stamp.length() == 10 ? time_stamp+"000" : time_stamp;

        SimpleDateFormat format =  new SimpleDateFormat("MM-dd");
        if(time_stamp.equals("")){

            return "";

        }else {

            Long time_long = new Long(Long.parseLong(true_time));

            String time = format.format(time_long);

            return time;
        }
    }

    public static String getTime6(String time_stamp){

        String true_time = time_stamp.length() == 10 ? time_stamp+"000" : time_stamp;

        SimpleDateFormat format =  new SimpleDateFormat("yyyy年MM月dd日");

        if(time_stamp.equals("")){

            return "";

        }else {
            Long time_long = new Long(Long.parseLong(true_time));

            String time = format.format(time_long);

            return time;
        }
    }

    public static String getTime7(String time_stamp){

        String true_time = time_stamp.length() == 10 ? time_stamp+"000" : time_stamp;

        SimpleDateFormat format =  new SimpleDateFormat("dd日 HH时mm分");

        if(time_stamp.equals("")){

            return "";

        }else {
            Long time_long = new Long(Long.parseLong(true_time));

            String time = format.format(time_long);

            return time;
        }
    }

    public static String F_num(String num){

        if(num.equals("")){

            return "0";

        }else {

            Float price = Float.valueOf(num);
            DecimalFormat format = new DecimalFormat("#.##");
            num = format.format(price);

            if (num.indexOf(".") > 0) {
                num = num.replaceAll("0+?$", "");
                num = num.replaceAll("[.]$", "");
            }
            return num;
        }
    }

    public  static String dataOne(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss",
                CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return times;
    }

    public static String dataTwo(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd",
                CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return times;
    }

    public static String dataThree(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("HH:mm",
                CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return times;
    }

    public static String dataFour(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy年MM月dd日",
                CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return times;
    }

    public static String dataFive(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                CHINA);
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return times;
    }

    public static String ToSBC(String input) {
        // 半角转全角：
        char[] c = input.toCharArray();
        for (int i = 0; i< c.length; i++) {
            if (c[i] == 32) {
                c[i] = (char) 12288;
                continue;
            }
            if (c[i]< 127)
                c[i] = (char) (c[i] + 65248);
        }
        return new String(c);
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[34578]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    /**
     * 验证车牌
     */
    public static boolean isPlateNO(String plates) {

        String plateRegex = "^[\\u4e00-\\u9fa5]{1}[A-Za-z]{1}[A-Za-z_0-9]{5}$";
        if (TextUtils.isEmpty(plates)) return false;
        else return plates.matches(plateRegex);
    }

    /**
     * 验证VIN码
     */
    public static boolean isVinNO(String vin) {

        String vinRegex = "^[0-9A-Za-z]{17}$";
        if (TextUtils.isEmpty(vin)) return false;
        else return vin.matches(vinRegex);
    }

    /**
     * 验证姓名
     */
    public static boolean isName(String name) {

        String nameRegex = "^[\\u4e00-\\u9fa5]{2,10}$";
        if (TextUtils.isEmpty(name)) return false;
        else return name.matches(nameRegex);
    }

    /**
     *判断当前应用程序处于前台还是后台
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static String getRunningActivityName(final Context context){
        ActivityManager activityManager=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        return runningActivity;
    }


//    邮箱验证
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strEmail);
        return m.matches();
    }


//    字母+数字验证
    public static boolean isPassword(String str) {
        String strPattern = "^[A-Za-z0-9]+$";
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 根据一个网络连接(String)获取bitmap图像
     *
     * @param imageUri
     * @return
     * @throws
     */
    public static Bitmap getbitmap(String imageUri) {
//        Log.v(TAG, "getbitmap:" + imageUri);
        // 显示网络上的图片
        Bitmap bitmap = null;

        try {
            URL myFileUrl = new URL(imageUri);
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();

//            Log.v(TAG, "image download finished." + imageUri);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            bitmap = null;
        } catch (IOException e) {
            e.printStackTrace();
//            Log.v(TAG, "getbitmap bmp fail---");
            bitmap = null;
        }
        return bitmap;
    }

    /**
     * 获取链接中的参数
     * @param url
     * @return
     */
    public static HashMap<String, String> getUrlParams(String url){
        int index = url.indexOf("?");
        String argStr = url.substring(index+1);
        String[] argAry = argStr.split("&");
        HashMap<String,String> argMap = new HashMap<String,String>(argAry.length);
        for(String arg : argAry){
            System.out.println("arg:"+arg);
            String[] argAryT = arg.split("=");
            argMap.put(argAryT[0], argAryT[1]);
        }
        return argMap;
    }

    /**
     * 获取链接中的协议
     * @param url
     * @return
     */
    public static String getUrlScheme(String url){
        int index = url.indexOf(":");
        return url.substring(0, index);
    }



//    根据经纬度计算距离
    private static final  double EARTH_RADIUS = 6378137;

    private static double rad(double d)
    {
        return d * Math.PI / 180.0;
    }

    public static double LantitudeLongitudeDist(double lon1, double lat1,double lon2, double lat2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);

        double radLon1 = rad(lon1);
        double radLon2 = rad(lon2);

        if (radLat1 < 0)
            radLat1 = Math.PI / 2 + Math.abs(radLat1);// south
        if (radLat1 > 0)
            radLat1 = Math.PI / 2 - Math.abs(radLat1);// north
        if (radLon1 < 0)
            radLon1 = Math.PI * 2 - Math.abs(radLon1);// west
        if (radLat2 < 0)
            radLat2 = Math.PI / 2 + Math.abs(radLat2);// south
        if (radLat2 > 0)
            radLat2 = Math.PI / 2 - Math.abs(radLat2);// north
        if (radLon2 < 0)
            radLon2 = Math.PI * 2 - Math.abs(radLon2);// west
        double x1 = EARTH_RADIUS * Math.cos(radLon1) * Math.sin(radLat1);
        double y1 = EARTH_RADIUS * Math.sin(radLon1) * Math.sin(radLat1);
        double z1 = EARTH_RADIUS * Math.cos(radLat1);

        double x2 = EARTH_RADIUS * Math.cos(radLon2) * Math.sin(radLat2);
        double y2 = EARTH_RADIUS * Math.sin(radLon2) * Math.sin(radLat2);
        double z2 = EARTH_RADIUS * Math.cos(radLat2);

        double d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)+ (z1 - z2) * (z1 - z2));
        //余弦定理求夹角
        double theta = Math.acos((EARTH_RADIUS * EARTH_RADIUS + EARTH_RADIUS * EARTH_RADIUS - d * d) / (2 * EARTH_RADIUS * EARTH_RADIUS));
        double dist = theta * EARTH_RADIUS;
        return dist;
    }

    public static void Call(Context context,String phone){

        Intent intent = new Intent(Intent.ACTION_DIAL);

        Uri data = Uri.parse("tel:" + phone);

        intent.setData(data);

        context.startActivity(intent);

    }

}
